package com.smartad.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class MyConfig {

	final static String CONFIG_FILE = "server.config";
	static MyConfig singleton = null;

	int _socketPort = 3098;
	int _httpPort = 3099;

	protected MyConfig() {
		loadSettingsFromExternal();
	}

	public static MyConfig getInstance() {
		if (singleton == null) {
			synchronized (MyConfig.class) {
				singleton = new MyConfig();
			}
		}
		return singleton;
	}
	
	public int getSocketPort() {
		return _socketPort;
	}
	
	public void setSocketPort(int socketPort) {
		_socketPort = socketPort;
	}

	public int getHttpPort() {
		return _httpPort;
	}
	
	public void setHttpPort(int httpPort) {
		_httpPort = httpPort;
	}

	void loadSettingsFromExternal() {

		Properties prop = new Properties();
		InputStream input = null;
		OutputStream output = null;

		try {
			String filepath = getFileAbsolutePath(CONFIG_FILE);

			File f = new File(filepath);
			if (f.exists()) {
				input = new FileInputStream(filepath);

				// load a properties file
				prop.load(input);

				_socketPort = Integer.parseInt(prop.getProperty("socket_port"));
				_httpPort = Integer.parseInt(prop.getProperty("http_port"));
			} else {
				output = new FileOutputStream(filepath);

				// set the properties value
				prop.setProperty("socket_port", Integer.toString(_socketPort));
				prop.setProperty("http_port", Integer.toString(_httpPort));

				// save properties to project root folder
				prop.store(output, null);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
					input = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (output != null) {
				try {
					output.close();
					output = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String getFileAbsolutePath(String filename) {
		// new File(".").getAbsolutePath(); // run directory, not jar
		// System.getProperty("user.dir");  // working directory
		String folder = MyConfig.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		// On running in eclipse, folder is the "./bin" directory
		// On running from jar in win or ubuntu, folder is the ".jar" file
		// So I get its parent directory.
		String filepath = new File(folder).getParent() + "/" + filename;
		com.smartad.common.Log.d("Doing access " + filepath);
		return filepath;
	}
}
